<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>My Redux</title>
  </head>
  <body>
    <button id="increment">+1</button>
    <span id="box">0</span>
    <button id="decrement">-1</button>
    <script src="myRedux.js"></script>
    <script src="middlewares/logger.js"></script>
    <script src="middlewares/thunk.js"></script>
    <script>

      function enhancer (createStore) {
        return function (reducer, preloadedState) {
          var store = createStore(reducer, preloadedState);
          var dispatch = store.dispatch;
          function _dispatch (action) {
            if (typeof action === 'function') {
              return action(dispatch)
            }
            dispatch(action);
          }
          return {
            ...store,
            dispatch: _dispatch
          }
        }
      }

      function counterReducer(state, action) {
        switch (action.type) {
          case "increment":
            return state + 1;
          case "decrement":
            return state - 1;
          default:
            return state;
        }
      }

      var rootReducer = combineReducers({counter: counterReducer})

      var store = createStore(rootReducer, {counter:100}, applyMiddleware(logger, thunk));
      // console.log('init state', store.getState())

      // 订阅store 监听状态改变
      store.subscribe(function () {
        document.getElementById("box").innerHTML = store.getState().counter;
      });

      var actions = bindActionCreators({increment, decrement}, store.dispatch);

      function increment () {
        return {type: "increment"}
      }

      function decrement () {
        return {type: "decrement"};
      }
      
      // +1按钮点击事件
      document.getElementById("increment").onclick = function () {
        // 触发 action 让数值+1
        // store.dispatch({ type: "increment" });
        // store.dispatch(function(dispatch){
        //   setTimeout(function(){
        //     dispatch({ type: "increment" });
        //   },1000)
        // });

        // logger -> thunk -> reducer
        // store.dispatch({ type: "increment" });

        actions.increment()
      };

      // -1按钮点击事件
      document.getElementById("decrement").onclick = function () {
        // 触发 action 让数值+1
        // store.dispatch({ type: "decrement" });

        actions.decrement()
      };
    </script>
  </body>
</html>
